package com.examples.service.impl;

import static com.examples.constant.IsvProduceConstant.DEBUG_TEST;

import com.examples.constant.ChangeStatus;
import com.examples.constant.RenewAction;
import com.examples.model.AppInfo;
import com.examples.model.NewInstanceInfo;
import com.examples.model.NewInstanceReq;
import com.examples.model.OrderQueryRsp;
import com.examples.model.QueryInstanceReq;
import com.examples.model.RefreshInstanceReq;
import com.examples.model.ReleaseInstanceReq;
import com.examples.model.UpdateInstanceStatusReq;
import com.examples.model.UpgradeInstanceReq;
import com.examples.service.ExternalService;
import com.examples.service.IsvProduceService;
import com.examples.util.CustomException;
import com.examples.util.IsvProduceAPI;
import com.examples.util.ResultCodeEnum;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Collections;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.CompletableFuture;

@Component
public class IsvProduceServiceImpl implements IsvProduceService {

    @Autowired
    private ExternalService externalService;

    @Override
    public String newInstance(NewInstanceReq newInstanceReq) {

        // 调测消息
        if (DEBUG_TEST.equals(newInstanceReq.getTestFlag())) {
            return UUID.randomUUID().toString();
        }

        // 查询订单详情
        OrderQueryRsp orderRsp = externalService.queryOrderInfo(newInstanceReq.getOrderId(),
            newInstanceReq.getOrderLineId());
        if (null == orderRsp || null == orderRsp.getOrderInfo()) {
            throw new CustomException(ResultCodeEnum.OTHER_INNER_ERROR.getResultCode(),
                "get order detail from KooGallery failed.");
        }

        // 生成实例
        String instanceId = UUID.randomUUID().toString();

        // 生成账号、密码、调用url
        // TODO

        // 保存订单、实例、账号等信息
        // TODO

        return instanceId;
    }

    @Override
    public String newInstance4Async(NewInstanceReq newInstanceReq) {
        if (DEBUG_TEST.equals(newInstanceReq.getTestFlag())) {
            return UUID.randomUUID().toString();
        }
        // 生成实例
        String instanceId = UUID.randomUUID().toString();
        CompletableFuture.runAsync(() -> {
            // 查询订单详情
            OrderQueryRsp orderRsp = externalService.queryOrderInfo(newInstanceReq.getOrderId(),
                newInstanceReq.getOrderLineId());
            if (null == orderRsp || null == orderRsp.getOrderInfo()) {
                throw new CustomException(ResultCodeEnum.OTHER_INNER_ERROR.getResultCode(),
                    "get order detail from KooGallery failed.");
            }

            // 生成账号、密码、调用url
            // TODO

            // 保存订单、实例、账号等信息
            // TODO
        });

        return instanceId;
    }

    @Override
    public List<NewInstanceInfo> queryInstance(QueryInstanceReq queryInstanceReq) {
        // 调测消息
        if (DEBUG_TEST.equals(queryInstanceReq.getTestFlag())) {
            NewInstanceInfo info = new NewInstanceInfo();
            info.setInstanceId(queryInstanceReq.getInstanceId());
            AppInfo application = new AppInfo();
            application.setAdminUrl("https://xxx");
            application.setFrontEndUrl("https://xxx");
            application.setUserName("testAccount");
            application.setPassword("");
            application.setMemo(IsvProduceAPI.toUnicodeString("please change your password after first login!"));
            info.setAppInfo(application);
            return Collections.singletonList(info);
        }
        // 查询数据库，获取instance实例详情
        // TODO

        NewInstanceInfo info = new NewInstanceInfo();
        AppInfo application = new AppInfo();
        // 根据查询到的instance实例详情，回填实例ID、管理地址、前台地址、管理员帐号、管理员初始密码
        // TODO

        application.setMemo(IsvProduceAPI.toUnicodeString("please change your password after first login!"));
        info.setAppInfo(application);
        return Collections.singletonList(info);
    }

    @Override
    public void refreshInstance(RefreshInstanceReq refreshInstanceReq) {
        if (DEBUG_TEST.equals(refreshInstanceReq.getTestFlag())) {
            return;
        }
        // 查询数据库，获取instance实例详情
        // TODO

        switch (refreshInstanceReq.getActivity()) {
            case RenewAction.SUB:
                // add a new formal application information
                // TODO
                break;
            case RenewAction.RENEW:
                // update the expire time
                // TODO
                break;
            case RenewAction.UNSUB:
                // update the expire time and a task to limit the instance information be used.
                // TODO
                break;
            default:
                break;
        }
    }

    @Override
    public void updateInstanceStatus(UpdateInstanceStatusReq updateInstanceStatusReq) {
        // query the instance information
        // TODO

        switch (updateInstanceStatusReq.getStatus()) {
            case ChangeStatus.FREEZE:
                // update the user resource or instance status to limit the instance information could be used.
                // TODO
                break;
            case ChangeStatus.UNFREEZE:
                // update the user resource or instance status to allow the instance information could be used.
                // TODO
                break;
            default:
                break;
        }
    }

    @Override
    public void releaseInstance(ReleaseInstanceReq releaseInstanceReq) {
        // TODO
    }

    @Override
    public void upgradeInstance(UpgradeInstanceReq upgradeInstanceReq) {
        // 查询订单详情
        OrderQueryRsp orderRsp = externalService.queryOrderInfo(upgradeInstanceReq.getOrderId(),
            upgradeInstanceReq.getOrderLineId());
        if (null == orderRsp || null == orderRsp.getOrderInfo()) {
            throw new CustomException(ResultCodeEnum.OTHER_INNER_ERROR.getResultCode(),
                "get order detail from KooGallery failed.");
        }

        // 更新实例关联的订单和商品信息
        // TODO
    }
}
